/////////////////////////////////////////////////////////////////////////////
// Original code from libhdfs3. Copyright (c) 2013 - 2014, Pivotal Inc.
// All rights reserved. Author: Zhanwei Wang
/////////////////////////////////////////////////////////////////////////////
//  Modifications by Kumo Inc.
// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//



#pragma once

#include <string.h>
#include <string>
#include <vector>
#include <cctype>

namespace Hdfs {
namespace Internal {

static inline std::vector<std::string> StringSplit(const std::string & str,
        const char * sep) {
    char * token, *lasts = NULL;
    std::string s = str;
    std::vector<std::string> retval;
    token = strtok_r(s.data(), sep, &lasts);

    while (token) {
        retval.push_back(token);
        token = strtok_r(NULL, sep, &lasts);
    }

    return retval;
}

static inline  std::string StringTrim(const std::string & str) {
    int start = 0, end = str.length();

    for (; start < static_cast<int>(str.length()); ++start) {
        if (!std::isspace(str[start])) {
            break;
        }
    }

    for (; end > 0; --end) {
        if (!std::isspace(str[end - 1])) {
            break;
        }
    }

    return str.substr(start, end - start);
}

static inline bool StringReplace(std::string& str, const std::string& from,
                           const std::string& to) {
    size_t start_pos = str.find(from);

    if (start_pos == std::string::npos) {
        return false;
    }

    str.replace(start_pos, from.length(), to);
    return true;
}

static inline bool StringReplaceAll(std::string& str, const std::string& from,
                              const std::string& to) {

    if (from.empty()) {
        return false;
    }

    bool retval = false;
    size_t start_pos = 0;

    while ((start_pos = str.find(from, start_pos)) != std::string::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length();
        retval = true;
    }

    return retval;
}
}
}
